import { isPlainObject, deepMerge } from './util'
import { METHODS } from '../types/index'
function normalizeHeadersName(headers: any, normalizeName: string): any {
  if (!headers) {
    return headers
  }
  Object.keys(headers).forEach(name => {
    if (name !== normalizeName && name.toUpperCase() === normalizeName.toUpperCase()) {
      headers[normalizeName] = headers[name]
      delete headers[name]
    }
  })
}

export function paraseHeaders(headers: any, data: any): any {
  normalizeHeadersName(headers, 'Content-Type')
  if (isPlainObject(data)) {
    if (headers && !headers['Content-Type']) {
      headers['Content-Type'] = 'application/json;charset=utf-8'
    }
  }
  return headers
}

/**
 * 处理response的header，将string转换为json对象形式
 *
 * @export
 * @param {string} headers
 * @returns {*}
 */
export function transformResponseHeader(headers: string): any {
  let parsed = Object.create(null)
  if (!headers) {
    return parsed
  }
  let headerList = headers.split('\r\n')
  headerList.forEach(header => {
    let [key, val] = header.split(':')
    key = key.trim().toLowerCase()
    if (!key) {
      return
    }
    if (val) {
      val = val.trim()
    }
    parsed[key] = val.trim()
  })
  return parsed
}

export function flatterHeaders(headers: any, method: METHODS): any {
  if (!headers) {
    return headers
  }
  headers = deepMerge(headers.common || {}, headers[method] || {}, headers)

  const methodsToDelete = ['delete', 'get', 'head', 'options', 'post', 'put', 'patch', 'common']

  methodsToDelete.forEach(method => {
    delete headers[method]
  })

  return headers
}
